package com.ogawa.project6602.activity

import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.bean.LoadState
import com.ogawa.musicmodule.MusicProjectSpUtils
import com.ogawa.musicmodule.MusicService
import com.ogawa.musicmodule.bean.MusicStartOrStopEvent
import com.ogawa.musicmodule.bean.UpdateMusicCurrentTimeEvent
import com.ogawa.project6602.R
import com.ogawa.project6602.adapter.MusicHunYinListAdapter
import com.ogawa.project6602.adapter.MusicHunYinPlayAdapter
import com.ogawa.project6602.adapter.MusicNaoboAdapter
import com.ogawa.project6602.base.Base6602MqttActivity
import com.ogawa.project6602.dialog.AdjustMusicBottomDialog
import com.ogawa.project6602.viewmodel.MusicViewModel
import com.ogawa.projectcommon.constants.IntentKeyConstant
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.projectcommon.utils.DataStatusViewUtils
import kotlinx.android.synthetic.main.activity_music_sleep.*
import org.greenrobot.eventbus.EventBus
import java.util.*


const val MUSIC_STATUS_WAIT_DOWN = 0
const val MUSIC_STATUS_SUSPEND = 1
const val MUSIC_STATUS_PLAY_ING = 2
const val MUSIC_STATUS_EMPTY = 10
const val MUSIC_STATUS_READY = 11

@Route(path = UrlPathConstant.ACTIVITY_6602_MUSIC_SLEEP)
class MusicSleepActivity : Base6602MqttActivity(), View.OnClickListener {
    lateinit var musicNaoboAdapter: MusicNaoboAdapter
    lateinit var musicHunYinListAdapter: MusicHunYinListAdapter
    lateinit var musicHunYinPlayAdapter: MusicHunYinPlayAdapter
    lateinit var musicViewModel: MusicViewModel
    override fun getLayoutId(): Int {
        return R.layout.activity_music_sleep
    }

    override fun initView() {
        super.initView()
        setTitle(getString(R.string.music_sleep))
        startService(Intent(this, MusicService::class.java))
        tvMusicAdjust.setOnClickListener(this)
        tvStart.setOnClickListener(this)
        allTimeTv.setOnClickListener(this)
        searchMixEt.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                p0?.let {
                    musicViewModel.searchHunyin(it.toString())
                }
            }
            override fun afterTextChanged(p0: Editable?) {

            }

        })
        LiveEventBus.get(IntentKeyConstant.LIVE_EVENT_BUS_KEY_MUSIC_CURTIME,
            UpdateMusicCurrentTimeEvent::class.java).observe(this, Observer {cutTime->
            val musicAllTime = MusicProjectSpUtils.getMusicAllTime()
            mCircleProgressBar.setmMaxProgress(musicAllTime.toInt())
            mCircleProgressBar.setProgress(cutTime.time.toInt())
            if (cutTime.time<=0){
                musicViewModel.stopAllMusic(mActivity)
            }

        })
        setViewModel()
        initRv()
        musicViewModel.getMusicList(mActivity)
    }

    private fun setViewModel() {
        musicViewModel = ViewModelProvider(this).get(MusicViewModel::class.java)
        musicViewModel.musicAllTimeObx.observe(this, Observer {
            allTimeTv.setText("${(it/60).toInt()}")
        })
        musicViewModel.loadState.observe(this, Observer {
            when (it) {
                is LoadState.Loading -> {
                    showLoadingDialog(canceledOnTouchOutside = false)
                }
                is LoadState.Fail -> {
                    dismissLoadingDialog()
                    ToastUtils.showShort(it.msg)
                }
                is LoadState.Success -> {
                    dismissLoadingDialog()
                }
            }
        })
        musicViewModel.downFileProgressStr.observe(this, Observer {
            if (it.isNotEmpty()) {
                showLoadingDialog(
                    it,
                    canceledOnTouchOutside = false,
                    dismissListener = object : DialogInterface.OnDismissListener {
                        override fun onDismiss(p0: DialogInterface?) {
                            musicViewModel.cancelDownMusicFile()
                        }
                    })
            } else {
                dismissLoadingDialog()
            }
        })
        musicViewModel.musicNaoBoAdapterBeans.observe(this, Observer {
            musicNaoboAdapter.setNewData(it)
        })
        musicViewModel.musicHunYinAdapterBeans.observe(this, Observer {
            musicHunYinListAdapter.setNewData(it)
        })
        musicViewModel.mixMusicplayBeans.observe(this, Observer {
            musicHunYinPlayAdapter.setNewData(it)
        })
        musicViewModel.beanIndexValue.observe(this, Observer {
            when (it.notifListType) {
                0 -> {
                    if (it.index == -1) {
                        musicNaoboAdapter.notifyDataSetChanged()
                    } else {
                        musicNaoboAdapter.notifyItemChanged(it.index)
                    }
                }
                1 -> {
                    if (it.index == -1) {
                        musicHunYinPlayAdapter.notifyDataSetChanged()
                    } else {
                        musicHunYinPlayAdapter.notifyItemChanged(it.index)
                    }
                }
                2 -> {
                    if (it.index == -1) {
                        musicHunYinListAdapter.notifyDataSetChanged()
                    } else {
                        musicHunYinListAdapter.notifyItemChanged(it.index)
                    }
                }
            }

            var isStart = false
            for (item in musicNaoboAdapter.data){
                if (item.status == MUSIC_STATUS_PLAY_ING){
                    isStart = true
                }
            }
            for (item in musicHunYinPlayAdapter.data){
                if (item.status == MUSIC_STATUS_PLAY_ING){
                    isStart = true
                }
            }
            if (isStart){
                tvStart.isSelected = false
                tvStart.text = getString(R.string.pause)
            }else{
                tvStart.isSelected = true
                tvStart.text = getString(R.string.start)
            }
            EventBus.getDefault().post(MusicStartOrStopEvent(isStart))

        })
    }





    private fun initRv() {
        musicNaoboAdapter = MusicNaoboAdapter()
        naoboMusicRv.layoutManager = LinearLayoutManager(this)
        naoboMusicRv.setHasFixedSize(true)
        musicNaoboAdapter.setOnItemClickListener { _, _, position ->
            val musicNaoBoBean = musicNaoboAdapter.data[position]
            if (musicNaoBoBean.status == MUSIC_STATUS_WAIT_DOWN) {
                musicViewModel.downMusicFile(
                    mActivity,
                    musicNaoBoBean.downUrl,
                    musicNaoBoBean.name,
                    true,
                    position
                )
            } else {
                musicViewModel.changeNaoBoMusic(mActivity, position)
            }
        }
        musicNaoboAdapter.emptyView = DataStatusViewUtils.getView(
            this,
            DataStatusViewUtils.DATA_EMPTY,
            getString(R.string.status_no_list),
            Color.TRANSPARENT,
            null
        ).run {
            this.setPadding(0, 0, 0, 0)
            return@run this
        }
        naoboMusicRv.adapter = musicNaoboAdapter

        musicHunYinPlayAdapter = MusicHunYinPlayAdapter()
        hunyinPlayRv.layoutManager = GridLayoutManager(this, 3)
        hunyinPlayRv.setHasFixedSize(true)
        musicHunYinPlayAdapter.setOnItemClickListener { _, _, position ->
            musicViewModel.chnagePlayMix(mActivity, position)
        }
        hunyinPlayRv.adapter = musicHunYinPlayAdapter


        musicHunYinListAdapter = MusicHunYinListAdapter()
        musicHunYinListAdapter.setOnItemClickListener { _, _, position ->
            val musicHunYinBean = musicHunYinListAdapter.data[position]
            if (musicHunYinBean.status == MUSIC_STATUS_WAIT_DOWN) {
                musicViewModel.downMusicFile(
                    mActivity,
                    musicHunYinBean.downUrl,
                    musicHunYinBean.name,
                    false,
                    position
                )
            } else {
                musicViewModel.addHunYin(mActivity, position)
            }
        }
        musicHunYinListAdapter.emptyView = DataStatusViewUtils.getView(
            this,
            DataStatusViewUtils.DATA_EMPTY,
            getString(R.string.status_no_list),
            Color.TRANSPARENT,
            null
        )
        hunyinMusicRv.layoutManager = GridLayoutManager(this, 4)
        hunyinMusicRv.setHasFixedSize(true)
        hunyinMusicRv.adapter = musicHunYinListAdapter
    }


    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tvMusicAdjust -> {
                var adjustMusicBottomDialog = AdjustMusicBottomDialog()
                adjustMusicBottomDialog.show(supportFragmentManager, "AdjustMusicBottomDialog")
            }
            R.id.tvStart->{
                if (tvStart.isSelected){
                    musicViewModel.startAllMusic(mActivity)
                }else{
                    musicViewModel.stopAllMusic(mActivity)
                }
            }
            R.id.allTimeTv->{
                musicViewModel.changeAllTime()
            }
        }
    }


}